package DEMO;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;



public class CreateXML {
	public static void main (String[] args){
		
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = factory.newDocumentBuilder();
			
			// root element
			Document doc = docBuilder.newDocument();
			Element rootElement = doc.createElement("ThongTinSV");
			doc.appendChild(rootElement);
			
			//MSSV element
			Element MS = doc.createElement("MSSV");
			rootElement.appendChild(MS);
				//set attribute to HoTen element
				Attr attrMS = doc.createAttribute("ID");
				attrMS.setValue("20112114");
				MS.setAttributeNode(attrMS);
				
			//HoTen element
			Element hoTen = doc.createElement("HoTen");
			hoTen.appendChild(doc.createTextNode("Ho Van Tan"));
			MS.appendChild(hoTen);
				
			//NamSinh element
			Element namSinh = doc.createElement("NamSinh");
			namSinh.appendChild(doc.createTextNode("05/02/1993"));
			MS.appendChild(namSinh);
				
			//Lop element
			Element lop = doc.createElement("Lop");
			lop.appendChild(doc.createTextNode("CNTT-TT 2.2"));
			MS.appendChild(lop);
			
			//write the content into XML file
			TransformerFactory tranFactory = TransformerFactory.newInstance();
			Transformer trans = tranFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			File file = new File("D:\\ThongTin.xml");
			StreamResult result = new StreamResult(file);
			
			trans.transform(source, result);
			
			System.out.println("File da duoc luu");
			
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
